//--------------------------------------------------------------
//
// Qizhi Zhang 
// ezhung@gmail.com
// http://www.moorwind.com
//
//--------------------------------------------------------------
package reader.services
{
	import __AS3__.vec.Vector;
	
	import com.adobe.webapis.flickr.AuthPerm;
	import com.adobe.webapis.flickr.AuthResult;
	import com.adobe.webapis.flickr.FlickrService;
	import com.adobe.webapis.flickr.PagedPhotoList;
	import com.adobe.webapis.flickr.Photo;
	import com.adobe.webapis.flickr.User;
	import com.adobe.webapis.flickr.events.FlickrResultEvent;
	import com.adobe.webapis.flickr.methodgroups.Upload;
	
	import flash.events.IOErrorEvent;
	
	import mx.core.UIComponent;
	
	import reader.ApplicationFacade;
	import reader.model.IDraftProxy;
	import reader.model.IServiceProxy;
	import reader.model.vo.AlbumPhotosVO;
	import reader.model.vo.AlbumVO;
	import reader.model.vo.BlogSourceVO;
	import reader.model.vo.MediaVO;
	import reader.model.vo.PhotoVO;
	import reader.model.vo.ServiceVO;
	import reader.model.vo.UploadPhotoVO;
	import reader.utils.CryptoUtil;

	public class FlickrReaderService extends AbstractService 
										implements IGetAlbumAble, IUploadPhotoAble, ISubscribeAble
	{
		////////////////////////////////////////////////////////////////////////////////
		//private variables
		
		private var _isGetAlbumAble:Boolean;
		private var _isUploadPhotoAble:Boolean;
		private var _isSubscribeAble:Boolean;
		
		private var _service:FlickrService;
		private var _draftProxy:IDraftProxy;
		private var _flickAuthRequest:FlickAuthRequest;
		
		//////////////////////////////////////////////////////////////////////////////
		//constructor
		public function FlickrReaderService(service:ServiceVO, proxy:IServiceProxy, parent:UIComponent=null)
		{
			super(service, proxy, parent);
			this.initialize();
		}
		
		////////////////////////////////////////////////////////////////////////////////
		//methods
		
		//----------------------------------------------------------------------------
		//
		// service initialize
		//
		//----------------------------------------------------------------------------
		
		override protected function initialize():void
		{
			_service = new FlickrService(service.key);
			_service.secret = CryptoUtil.decrypt(service.secret, SERVICE_SECRET);
			_service.addEventListener(IOErrorEvent.IO_ERROR, onServiceError_handler, false, 0, true);
			_flickAuthRequest = new FlickAuthRequest(_service, service, proxy);
			
			if(!service.username || service.username == "")
			{
				requestFlickrName();
			}
			
		}
		
		private function requestFlickrName():void
		{
			_flickAuthRequest.request(onInitCallBack, AuthPerm.READ);
		}
		
		private function onInitCallBack(authResult:AuthResult):void
		{
			_service.token = authResult.token;
			_service.permission = authResult.perms;
			service.username = authResult.user.nsid;
			proxy.updateService(service);
		}
		
		//----------------------------------------------------------------------------
		//
		// get albums
		//
		//----------------------------------------------------------------------------

		public function get isGetAlbumAble():Boolean
		{
			return _isGetAlbumAble;
		}
		
		public function set isGetAlbumAble(value:Boolean):void
		{
			_isGetAlbumAble = value;
		}
		
		public function getAlbums():void
		{
			if(!_service)
			{
				initialize();
				return;
			}
			var ab:AlbumVO = new AlbumVO();
			ab.albumid = service.link;
			ab.title = service.name;
			ab.albumuri = "http://www.flickr.com/photos/" + service.username;
			ab.photosCount = -1;
			proxy.sendNotification(ApplicationFacade.GET_ALBUMS, Vector.<AlbumVO>([ab]), service.name);
		}		
		public function getAlbumPhotos(param:AlbumVO):void
		{
			_service.addEventListener(FlickrResultEvent.PEOPLE_GET_PUBLIC_PHOTOS, onGetFacebookAlbum_handler);
			_service.people.getPublicPhotos(service.username);
		}
		private function onGetFacebookAlbum_handler(e:FlickrResultEvent):void
		{
			_service.removeEventListener(FlickrResultEvent.PEOPLE_GET_PUBLIC_PHOTOS, onGetFacebookAlbum_handler);
			var p:PagedPhotoList = e.data.photos as PagedPhotoList;
			var ap:AlbumPhotosVO = new AlbumPhotosVO();
			ap.title = service.name;
			ap.photosCount = p.photos.length;
			for(var i:int = 0; i < p.photos.length; i++)
			{
				var av:PhotoVO = new PhotoVO();
				var ph:Photo = p.photos[i];
				av.caption = ph.title;
				av.imageuri = creatImageURL(ph, "b");
				av.photoid = ph.id;
				av.smallimageuri = creatImageURL(ph, "s");
				ap.list.push(av);
			}
			ap.defaultimage = ap.list[0].smallimageuri;
			proxy.sendNotification(ApplicationFacade.GET_ALBUM_PHOTOS, ap, service.name);
		}
		
		//----------------------------------------------------------------------------
		//
		// upload photo
		//
		//----------------------------------------------------------------------------
		
		public function get iDraftProxy():IDraftProxy
		{
			return _draftProxy;
		}
		
		public function set iDraftProxy(proxy:IDraftProxy):void
		{
			_draftProxy = proxy;
		}
		
		public function get isUploadPhotoAble():Boolean
		{
			return _isUploadPhotoAble;
		}
		
		public function set isUploadPhotoAble(value:Boolean):void
		{
			_isUploadPhotoAble = value;
		}
		
		private var file:UploadPhotoVO;
		private var filename:String;
		public function uploadPhotos(file:UploadPhotoVO, album:AlbumVO = null):void
		{
			if(!_service)
			{
				initialize();
				return;
			}
			this.file = file;
			_flickAuthRequest.request(uploadPhoto, AuthPerm.WRITE);
		}
		private function uploadPhoto(authResult:AuthResult):void
		{
			_service.addEventListener(FlickrResultEvent.PHOTOS_UPLOAD_COMPLETE, onFlickrUpload_handler);
			var up:Upload = _service.photos.upload;
			up.binaryUpload(file.image, file.extension);
			filename = file.fileName;
			file = null;
		}
		private function onFlickrUpload_handler(e:FlickrResultEvent):void
		{
			_service.removeEventListener(FlickrResultEvent.PHOTOS_UPLOAD_COMPLETE, onFlickrUpload_handler);
			_service.addEventListener(FlickrResultEvent.PHOTOS_GET_INFO, onPhotosGerInfo_handler);
			_service.photos.getInfo(e.data.toString());
		}
		private function onPhotosGerInfo_handler(e:FlickrResultEvent):void
		{
			_service.removeEventListener(FlickrResultEvent.PHOTOS_GET_INFO, onPhotosGerInfo_handler);
			var ph:Photo = e.data.photo as Photo;
			var av:PhotoVO = new PhotoVO();
			if(ph)
			{
				av.caption = ph.title
				av.imageuri = creatImageURL(ph, "b");
				av.photoid = ph.id;
				av.smallimageuri = creatImageURL(ph, "s");
			}
			var media:MediaVO = new MediaVO(av);
			media.name = filename;
			media.platform = service.name;
			iDraftProxy.saveMedia(media);
			proxy.sendNotification(ApplicationFacade.UPLOAD_PHOTO, av, service.name);
			filename = null;
		}
		
		private function creatImageURL(photo:Photo, size:String):String
		{
			return "http://farm" + photo.farm + ".static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_" + size + ".jpg";
		}
		
		//----------------------------------------------------------------------------
		//
		// add Subscribe
		//
		//----------------------------------------------------------------------------
		
		public function get isSubscribeAble():Boolean
		{
			return _isSubscribeAble;
		}
		
		public function set isSubscribeAble(value:Boolean):void
		{
			_isSubscribeAble = value;
		}
		
		public function addSubscribe():void
		{
			if(!_service)
			{
				initialize();
				return;
			}
			_service.addEventListener(FlickrResultEvent.CONTACTS_GET_PUBLIC_LIST, onGetPublicList_handler);
			_service.contacts.getPublicList(service.username);
		}
		private function onGetPublicList_handler(e:FlickrResultEvent):void
		{
			_service.removeEventListener(FlickrResultEvent.CONTACTS_GET_PUBLIC_LIST, onGetPublicList_handler);
			var contects:Array = e.data.contacts;
			var list:Vector.<BlogSourceVO> = new Vector.<BlogSourceVO>();
			for(var i:int = 0; i < contects.length; i++)
			{
				var fr:User = contects[i];
				var bs:BlogSourceVO = new BlogSourceVO();
				bs.blogLink = "http://www.flickr.com/photos/" + fr.nsid;
				bs.blogName = fr.username;
				bs.blogRSS = "http://api.flickr.com/services/feeds/photos_public.gne?id=" + fr.nsid + "&lang=en-us&format=rss_200";
				list.push(bs);	
			}
			proxy.sendNotification(ApplicationFacade.SERVICE_SUBSCRIBES, list, service.sid.toString());
		}
	}
}

import reader.model.vo.ServiceVO;
import reader.model.IServiceProxy;
import reader.utils.URL;

import com.adobe.webapis.flickr.FlickrService;
import com.adobe.webapis.flickr.events.FlickrResultEvent;
import com.adobe.webapis.flickr.AuthResult;

class FlickAuthRequest
{
	////////////////////////////////////////////////////////////////////////////////
	//private variables
	
	private var flickr:FlickrService;
	private var service:ServiceVO;
	private var callback:Function;
	private var proxy:IServiceProxy;
	
	private var authperm:String;
	private var frob:String;
	
	//////////////////////////////////////////////////////////////////////////////
	//constructor
	public function FlickAuthRequest(flickr:FlickrService, service:ServiceVO, proxy:IServiceProxy)
	{
		this.flickr = flickr;
		this.service = service;
		this.proxy = proxy;
	}
	
	////////////////////////////////////////////////////////////////////////////////
	//methods
		
	public function request(callback:Function, authperm:String):void
	{
		this.callback = callback;
		this.authperm = authperm;
		this.flickr.addEventListener(FlickrResultEvent.AUTH_GET_FROB, onGetFrob_handler);
		this.flickr.auth.getFrob();
	}
	
	private function onGetFrob_handler(e:FlickrResultEvent):void
	{
		this.flickr.removeEventListener(FlickrResultEvent.AUTH_GET_FROB, onGetFrob_handler);
		if(e.success)
		{
			frob = e.data.frob;
			service.login_url = flickr.getLoginURL(frob, authperm);
			proxy.requestAuthWindow(service, authCallBack);
		}
	}
	
	private function authCallBack(url:URL):void
	{
		flickr.addEventListener(FlickrResultEvent.AUTH_GET_TOKEN, getTokenResponse_handler);
        flickr.auth.getToken(frob); 		
	}
	
	private function getTokenResponse_handler(event:FlickrResultEvent):void
	{
		flickr.removeEventListener(FlickrResultEvent.AUTH_GET_TOKEN, getTokenResponse_handler);
		if(event.success)
		{
			var authResult:AuthResult = AuthResult(event.data.auth);
			callback(authResult);
		}
	}	
}